// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:audio_waveforms/audio_waveforms.dart';
import 'package:bruno/bruno.dart';
import 'package:common/common.dart';
import 'package:common/image/image_tools.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:miaowu/app/module/world/audio/recorder/recorder_manager.dart';

import '../../../world/world_audio_publish/water_button.dart';
import '../container_tab_indicator.dart';
import '../waveforms_player_widget.dart';
import 'audio_card_record_logic.dart';
import 'audio_card_record_restult_widget.dart';
import 'audio_card_record_state.dart';
import 'audio_record_config.dart';

/// @description:
/// @author
/// @date: 2025-01-20 09:58:27
class AudioCardRecordPage extends StatefulWidget {
  const AudioCardRecordPage({Key? key}) : super(key: key);

  @override
  State<AudioCardRecordPage> createState() => _AudioCardRecordPageState();
}

class _AudioCardRecordPageState extends State<AudioCardRecordPage> with SingleTickerProviderStateMixin {
  final AudioCardRecordLogic logic = Get.put(AudioCardRecordLogic());

  final AudioCardRecordState state = Get.find<AudioCardRecordLogic>().state;

  late final RecorderController recorderController;

  AudioCardState audioCardState = AudioCardState.initial;

  String? audioPath;
  int audioDuration = 0;
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);

    PermissionUtils.microphone();
    RecorderManager.instance.configRecordParams(minTime: 6, maxTime: 10);
    recorderController = RecorderManager.instance.init();
    RecorderManager.instance.onChangeState = (AudioCardState state, int duration, String fildPath) {
      setState(() {
        audioCardState = state;
        if (state == AudioCardState.recording) {
          // isRecording = true;
        } else if (state == AudioCardState.initial) {
          // isRecording = false;
          audioPath = null;
        } else if (state == AudioCardState.recordingCompleted) {
          // isRecording = false;
          audioPath = fildPath;
        }
      });
    };
    RecorderManager.instance.onCurrentDuration = (int duration) {
      setState(() {
        audioDuration = duration;
      });
    };
  }

  @override
  void dispose() {
    _tabController.dispose();
    RecorderManager.instance.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<AudioCardRecordLogic>(
      init: AudioCardRecordLogic(),
      initState: (_) {},
      builder: (_) {
        return state.audioRecordConfig == null
            ? const Center(child: CupertinoActivityIndicator())
            : Stack(
                children: [
                  SizedBox(
                      width: double.infinity,
                      child: Image.asset('assets/app/images/world/world_top_bg.png', fit: BoxFit.cover)),
                  Scaffold(
                    appBar: BrnAppBar(title: '声音卡片', backgroundColor: Colors.transparent),
                    backgroundColor: Colors.transparent,
                    body: Container(
                        color: Colors.white,
                        padding: EdgeInsets.only(
                            bottom: MediaQuery.of(context).padding.bottom == 0
                                ? 10
                                : (MediaQuery.of(context).padding.bottom - 10)),
                        child: state.audioRecordConfig!.editArea!.view == 1
                            ? _buildAudioEditWidgetsWarpper()
                            : _buildAudioResultWarpper()),
                  ),
                ],
              );
      },
    );
  }

  Widget _buildAudioResultWarpper() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        _buildAudioHeaderWarpper(),
        if (state.audioRecordConfig!.editArea!.view == 1) _buildAudioEditWidgetsWarpper(),
        if (state.audioRecordConfig!.playArea!.view == 1)
          AudioCardRecordRestultWidget(
              playArea: state.audioRecordConfig!.playArea!,
              deleteAudioCallBack: () {
                logic.deleteAudioResult();
              },
              againAudioCallBack: () {}),
      ],
    );
  }

  /// 编辑录音文件视图
  Widget _buildAudioEditWidgetsWarpper() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        _buildAudioHeaderWarpper(),
        if (state.audioRecordConfig!.editArea!.view == 1) _buildTabBarWarpper(),
        if (state.audioRecordConfig!.editArea!.view == 1)
          Expanded(
            child: state.audioRecordConfig!.editArea!.view != 1
                ? const SizedBox()
                : TabBarView(controller: _tabController, children: [
                    AudioExampelWidget(
                      key: const ValueKey('1'),
                      recordKind: state.audioRecordConfig!.editArea!.recordKind!.first,
                    ),
                    AudioExampelWidget(
                      key: const ValueKey(2),
                      recordKind: state.audioRecordConfig!.editArea!.recordKind!.last,
                    ),
                  ]),
          ),
        // _buildAudioWaveWarpper(context),
        if (state.audioRecordConfig!.editArea!.view == 1 && state.recordAudioBtn!.view == 1)
          _buildAudioButtonsWarpper(),
      ],
    );
  }

  Container _buildAudioHeaderWarpper() {
    return Container(
      height: 50.h,
      padding: EdgeInsets.symmetric(horizontal: 10.w),
      margin: EdgeInsets.symmetric(vertical: 6.w, horizontal: 20.5.w),
      decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(25.r)), color: Colors.white),
      child: Row(mainAxisAlignment: MainAxisAlignment.start, children: [
        Image.asset('assets/app/images/world/audio_mic.png', width: 30.w),
        Text('  ${state.audioRecordConfig?.title ?? '用声音show自己，让Ta听见更好的你~'}',
            style: TextStyle(color: Colors.black, fontSize: 14.sp)),
        SizedBox(width: 16.w),
      ]),
    );
  }

  SizedBox _buildAudioButtonsWarpper() {
    logs('audioCardState == $audioCardState');
    return SizedBox(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          if (audioPath != null) _buildDeleteAudioButtonWarpper(),
          audioPath != null ? _buildAudioPlayButtonWarpper() : _buildAudioRecordButtonWarpper(),
          if (audioPath != null) _buildFinshAudioButtonWarpper(),
        ],
      ),
    );
  }

// 录音完成按钮
  GestureDetector _buildFinshAudioButtonWarpper() {
    return GestureDetector(
      onTap: () {
        logic.submitReocrdResult(audioPath: audioPath ?? '', timelong: audioDuration.toString());
      },
      child: Container(
          margin: const EdgeInsets.only(right: 10),
          child: Column(
            children: [
              Image.asset('assets/app/images/world/audio_finish_icon.png', width: 36.w),
              const SizedBox(height: 3),
              Text('完成', style: TextStyle(color: Colors.black, fontSize: 13.sp))
            ],
          )),
    );
  }

// 录音按钮
  GestureDetector _buildAudioRecordButtonWarpper() {
    return GestureDetector(
      onTap: () {
        RecorderManager.instance.startOrStopRecording();
      },
      child: Container(
          padding: const EdgeInsets.only(bottom: 50),
          child: Column(
            children: [
              Stack(
                children: [
                  Container(
                      width: 100,
                      height: 100,
                      color: Colors.transparent,
                      child: audioCardState == AudioCardState.recording
                          ? const ACEWaterButton(color: Color(0xFFE9FAFA))
                          : const SizedBox()),
                  Positioned.fill(
                    child: Center(
                      child: Image.asset(
                          audioCardState == AudioCardState.recording
                              ? 'assets/app/images/world/audio_start_ing_icon.png'
                              : 'assets/app/images/world/audio_start_icon.png',
                          width: 80.w),
                    ),
                  ),
                  if (audioCardState == AudioCardState.recording)
                    Positioned.fill(
                        top: 35.h,
                        child: Center(
                            child: Text(
                          '${audioDuration}s',
                          style: TextStyle(color: Colors.white, fontSize: 13.sp, fontWeight: FontWeight.bold),
                        ))),
                ],
              ),
              Center(
                  child: Text(
                audioCardState == AudioCardState.recording ? '录制中' : '点击录制',
                style: TextStyle(color: Colors.black, fontSize: 16.sp, fontWeight: FontWeight.bold),
              ))
            ],
          )),
    );
  }

// 播放声音按钮
  Widget _buildAudioPlayButtonWarpper() {
    return WaveformsPlayerWidget(audioPath: audioPath ?? '');
  }

// 删除录音按钮
  GestureDetector _buildDeleteAudioButtonWarpper() {
    return GestureDetector(
      onTap: () {
        SmartDialog.show(
          usePenetrate: false,
          clickMaskDismiss: true,
          backType: SmartBackType.block,
          keepSingle: true,
          useAnimation: false,
          builder: (context) => Center(
            child: CustomAlertWidget(
              title: '温馨提示',
              content: "确认删除并清除聊天记录？\n",
              confirmText: '确定',
              confirmAction: () {
                RecorderManager.instance.deleteAudioFile(
                    audioPath: audioPath ?? '',
                    successCallback: () {
                      setState(() {
                        audioPath = null;
                        audioCardState = AudioCardState.initial;
                      });
                    });
              },
              cancemText: '取消',
            ),
          ),
        );
      },
      child: Container(
        margin: const EdgeInsets.only(left: 10),
        child: Column(
          children: [
            Image.asset('assets/app/images/world/audio_del_icon.png', width: 36.w),
            const SizedBox(height: 3),
            Text('删除', style: TextStyle(color: Colors.black, fontSize: 13.sp))
          ],
        ),
      ),
    );
  }

  Container _buildTabBarWarpper() {
    return Container(
      width: 212,
      height: 34,
      padding: const EdgeInsets.only(left: 0, right: 0),
      decoration: BoxDecoration(color: const Color(0xFFF1F6FF), borderRadius: BorderRadius.circular(17)),
      child: TabBar(
        controller: _tabController,
        labelStyle: const TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500),
        unselectedLabelStyle: const TextStyle(color: Colors.black, fontSize: 14, fontWeight: FontWeight.w500),
        isScrollable: false,
        onTap: (index) {
          logs(index);
        },
        dividerColor: Colors.transparent,
        indicator: const ContainerTabIndicator(
          color: Color(0xFF25D4D0),
          width: 104,
          height: 34,
          radius: BorderRadius.all(Radius.circular(14.0)),
          padding: EdgeInsets.only(left: 2.0, right: 2, top: 2.5, bottom: 2),
        ),
        tabs: const <Widget>[Tab(child: Text('自由录制')), Tab(child: Text('配文推荐'))],
      ),
    );
  }
}

class AudioExampelWidget extends StatefulWidget {
  const AudioExampelWidget({super.key, required this.recordKind});

  final RecordKind recordKind;

  @override
  State<AudioExampelWidget> createState() => _AudioExampelWidgetState();
}

class _AudioExampelWidgetState extends State<AudioExampelWidget> {
  void fetchReocrdTextList() {
    HttpProvider.get('/user/getEditVoiceText',
        params: {
          'txt_id': widget.recordKind.text?.id.toString(),
        },
        explain: '获取录制声音卡片的样板文字', success: (result) {
      TextItem item = TextItem.fromJson(result.data);
      widget.recordKind.text = item;
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    List<String> contents = (widget.recordKind.text?.txt ?? '').split('\r\n');
    return Container(
      padding: EdgeInsets.symmetric(vertical: 10, horizontal: 32.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            widget.recordKind.title ?? '让Ta进入你的“声音世界”',
            style: TextStyle(color: Colors.black, fontSize: 18.sp, fontWeight: FontWeight.w700),
          ),
          const SizedBox(height: 10),
          Expanded(
            child: Container(
              clipBehavior: Clip.hardEdge,
              decoration:
                  BoxDecoration(color: const Color(0xFFF1F6FF), borderRadius: BorderRadius.all(Radius.circular(19.r))),
              child: Column(
                children: [
                  Expanded(
                    child: ListView.builder(
                      padding: const EdgeInsets.symmetric(horizontal: 23, vertical: 20),
                      itemBuilder: (BuildContext cxt, int index) {
                        String value = contents[index];
                        return Container(
                            margin: EdgeInsets.only(bottom: 16.h),
                            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                            decoration: BoxDecoration(
                                color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(19.r))),
                            child: Text(value, style: TextStyle(color: Colors.black, fontSize: 18.sp)));
                      },
                      itemCount: contents.length,
                    ),
                  ),
                  if (widget.recordKind.key == 'rule')
                    GestureDetector(
                      onTap: () {
                        fetchReocrdTextList();
                      },
                      child: Container(
                        alignment: Alignment.centerRight,
                        color: Colors.transparent,
                        padding: const EdgeInsets.only(top: 6, bottom: 15, right: 15),
                        child: Text.rich(
                            TextSpan(style: TextStyle(fontSize: 12.sp, color: const Color(0xFF404A94)), children: [
                          WidgetSpan(
                              alignment: PlaceholderAlignment.middle,
                              child: Padding(
                                padding: const EdgeInsets.only(right: 10),
                                child: Image.asset('assets/app/images/world/audio_record_check.png', width: 14.5),
                              )),
                          const TextSpan(text: '换一换'),
                        ])),
                      ),
                    )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
